<?php
namespace Manage\Controller;

use Boris\DumpInspector;
use Think\Controller;
use Think\Model;


class VendorController extends BaseController{

    public function index() {
        $p = max(I('param.p'), 1);
        $num = max(I('param.num'), 20);
        $this->assign('page', $p);
        $this->assign('num', $num);

        $order_field = I('param.order_field', 'vendor_id');
        $order = I('param.order', 'desc');
        $sunxu = $order == 'asc' ? 'desc' : 'asc';
        $this->assign('order_field', $order_field);
        $this->assign('order', $sunxu);
        $order = array($order_field => $order);

        $search_field = I('param.search_field');
        $search = trim(I('param.search'));
        $where[0] = ' 1=1 ';
        if ($search && $search_field) {
            $where[] = $search_field." like '%".$search."%'";
            $this->assign('search',$search);
            $this->assign('search_field',$search_field);
        }
        $count = M('b2c_vendors')
            ->where($where)
            ->count();
        $Page = new \Think\Page($count, $num);
        $show = $Page->show();
        $data = M('b2c_vendors')
            ->page($p, $num)
            ->where($where)
            ->order($order)
            ->select();
        $this->assign('list',$data);
        $this->assign('page',$show);
        $this->display();
    }

    public function add() {
        $this->display('Vendor/edit');
    }

    public function edit() {
        if (IS_POST) {
            $data['vendor_id'] = I('post.vendor_id');
            $data['vendor_name'] = I('post.vendor_name');
            $data['vendor_full_name'] = I('post.vendor_full_name');
            $data['principal'] = I('post.principal');
            $data['tel'] = I('post.tel');
            $data['mobile'] = I('post.mobile');
            $data['vendor_status'] = I('post.vendor_status', '0');
            $data['update_time'] = time();
            if ($data['vendor_id']) {
                $res = M('b2c_vendors')->save($data);
            } else {
                unset($data['vendor_id']);
                $data['create_time'] = time();
                $res = M('b2c_vendors')->add($data);
            }
            if ($res !== false) {
                $this->success('成功!',U('vendor/index'));
            } else {
                $this->error('失败!');
            }
        } else {
            $vendor_id = I('get.vendor_id');
            $info = M('b2c_vendors')->where(array('vendor_id'=>$vendor_id))->find();
            $this->assign('info', $info);
            $this->display();
        }
    }

    //批量删除
    public function del() {
        if (IS_AJAX) {
            $vendor_id = I('param.vendor_id');
            if ($vendor_id) {
                if (is_array($vendor_id)) {
                    $vendor_id = join(',' ,$vendor_id);
                    $del = $vendor_id;
                    $res = M('b2c_vendors')->delete($del);

                } else {
                    $del = array('vendor_id'=>$vendor_id);
                    $res = M('b2c_vendors')->where($del)->delete();
                }
                if ($res !== false) {
                    $return = array(
                        'status'=>true,
                        'message'=>'删除成功',
                    );
                } else {
                    $return = array(
                        'status'=>false,
                        'message'=>'操作失败',
                    );
                }
            } else {
                $return = array(
                    'status'=>false,
                    'message'=>'供应商ID不能为空',
                );
            }
            $this->ajaxReturn($return);
        }

        if (empty($vendor_id)) {
            return false;
        }
    }

    public function products() {
        $vendor_id = I('get.vendor_id');
        if (!$vendor_id){
            $this->error('失败!');
        }
        $info = M('b2c_vendors')->where(array('vendor_id'=>$vendor_id))->find();
        $this->assign('info', $info);
        $page = max(I('param.p'), 1);
        $num = max(I('param.num'), 20);

        $order = " order by c.vendor_sum desc,a.product_id desc ";

        $search_field = I('param.search_field');
        $search = I('param.search');

        $where = " where d.product_type_id=2 and a.marketable='true'";
        if ($search && $search_field) {
            $where .= " and a.{$search_field} like '%{$search}%' ";
            $this->assign('search',$search);
            $this->assign('search_field',$search_field);
        }

        $db = new Model();
        $count = $db->query($this->_sql('count(*)', $vendor_id, $where));
        $Page = new \Think\Page($count[0]['count(*)'], $num);
        $show = $Page->show();
        $fields = array(
            'a.product_id pid',
            'a.goods_id gid',
            'a.barcode',
            'a.bn',
            'a.name',
            'a.price',
            'a.cost',
            'c.*',
        );
        $skip = ($page - 1) * $num;
        $limit = " limit {$skip},{$num} ";
        $list = $db->query($this->_sql($fields, $vendor_id, $where, $order, $limit));
        $this->assign('list',$list);
        $this->assign('page',$show);
        $this->display();

    }

    private function _sql($fields, $vendor_id, $where='', $order='', $limit='') {
        /**
         *  select a.product_id,a.name,a.barcode,a.bn,a.cost,a.price,c.* from sdb_b2c_products a
         *  left join sdb_b2c_product_relation d on a.product_id = d.product_id
         *  left join
         *  (select DISTINCT * from sdb_b2c_vendor_product b where b.vendor_id=11) c
         *  on a.product_id=c.product_id
         */
        if (is_array($fields)) {
            $fields = join(',', $fields);
        }
        return $sql = "select {$fields} from ".C('DB_PREFIX')."b2c_products a 
        left join sdb_b2c_product_relation d on a.product_id = d.product_id 
        left join (select DISTINCT * from ".C('DB_PREFIX')."b2c_vendor_product b where b.vendor_id={$vendor_id} ) c on a.product_id = c.product_id {$where} {$order} {$limit}";
    }

    /**ajax
     * 保存供应商提供的货品
     */
    public function save_edit() {
        $vendor_id = I('get.vendor_id');
        if (!$vendor_id) {
            $return = array(
                'status'=>false,
                'message'=>'缺少参数',
            );
            $this->ajaxReturn($return);
        }
        $data = I('post.data');
        $db = new Model();
        $db->startTrans();
        foreach ($data as $item) {
            if ($item['is_show'] == 'true') {
                $res = $this->save_product($item, $vendor_id);
            } else {
                $res = $this->save_remove($item['product_id'], $vendor_id);
            }
            if ($res === false) {
                break;
            }
        }

        if ($res !== false) {
            $db->commit();
            $return = array(
                'status'=>true,
                'message'=>'成功',
            );
        } else {
            $db->rollback();
            $return = array(
                'status'=>false,
                'message'=>'失败',
            );
        }
        $this->ajaxReturn($return);

    }

    /**保存供应商的货品编辑 如果存在执行更新 反之执行插入
     * @param $data
     * @param $vendor_id
     * @return bool
     */
    private function save_product($data, $vendor_id)
    {
        if(!$vendor_id || empty($data)) {
            return false;
        }
        $where = array(
            'product_id' => $data['product_id'],
            'vendor_id' => $vendor_id,
        );
        $info = M('b2c_vendor_product')->field('vgood_id')->where($where)->find();
        if ($info['vgood_id']) {
            //存在该条商品 执行更新
            $save = array(
                'vendor_price' => $data['vendor_price'],
                'vendor_sum' => $data['vendor_sum'],
            );
            $res = M('b2c_vendor_product')->where(array('vgood_id'=>$info['vgood_id']))->save($save);
        } else {
            //不存在该条商品 新增
            $add = array(
                'vendor_id' => $vendor_id,
                'goods_id' => $data['goods_id'],
                'product_id' => $data['product_id'],
                'vendor_price' => $data['vendor_price'],
                'vendor_sum' => $data['vendor_sum'],
            );
            $res = M('b2c_vendor_product')->add($add);
        }
        return $res !== false ? true: false;
    }

    /**如果有删除动作 先查询是否有 在执行删除数据
     * @param $product_id
     * @param $vendor_id
     * @return bool
     */
    private function save_remove($product_id, $vendor_id) {
        $res = true;
        $where = array(
            'product_id' => $product_id,
            'vendor_id' => $vendor_id,
        );
        $count = M('b2c_vendor_product')->where($where)->count();
        if ($count) {
            $res = M('b2c_vendor_product')->where($where)->delete();
        }
        return $res !== false ? true: false;
    }
}